package practice;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Day34 {

    //全序列
    List<Integer> path = new ArrayList<>();
    boolean[] flag;
    List<List<Integer>> list = new ArrayList<>();
    public List<List<Integer>> permute(int[] nums) {
        int n = nums.length;
        if(n == 0 || nums == null) {
            return list;
        }
        flag = new boolean[n];
        dfs(nums,0,n);
        return list;
    }
    private void dfs(int[] nums, int depth, int n) {
        if(depth == n) {
            list.add(path);
            return;
        }

        for(int i = 0; i < n; i++) {
            if(!flag[i]) {
                path.add(nums[i]);
                flag[i] = true;
                dfs(nums,depth+1,n);

                flag[i] = false;
                path.remove(path.size() - 1);
            }
        }
    }

    //子集
    public List<List<Integer>> subsets(int[] nums) {
        int n = nums.length;
        if(n == 0 || nums == null) {
            return list;
        }

        dfs(0,nums);
        return list;
    }
    private void dfs(int i, int[] nums) {
        list.add(new ArrayList<>(path));
        if(i == nums.length) {
            return;
        }
        for(int j = i; j < nums.length; j++) {
            path.add(nums[j]);
            dfs(j+1,nums);
            path.remove(path.size()-1);
        }
    }

    //组合总和
    int sum = 0;
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        if(candidates.length == 0 || candidates == null) {
            return list;
        }
        Arrays.sort(candidates);
        dfs(candidates,target,0,0);
        return list;
    }
    private void dfs(int[] candidates,int target,int depth,int start) {

        if(target == sum) {
            list.add(new ArrayList<>(path));
            return;
        }

        for(int i = start; i < candidates.length; i++) {
            if(sum > target) {
                break;
            }
            path.add(candidates[i]);
            sum += candidates[i];
            System.out.println(sum);
            dfs(candidates,target,depth+1,i);
            path.remove(path.size()-1);
            sum -= candidates[i];
        }
    }
    public static void main(String[] args) {
        Day34 day34 = new Day34();
        day34.combinationSum(new int[]{1,2},3);
    }
}
